using System.Collections.Generic;
using System.Web.Mvc;
using EPiServer.Community.Blog;
using JoelAbrahamsson.BlogExtensions;

namespace JoelAbrahamsson.Web.Controllers
{
    public class HomeController : Controller
    {
        ExtendedBlogHandlerFacade _blogHandlerFacade;
        private const int defaultEntryCount = 10;

        public HomeController(ExtendedBlogHandlerFacade blogHandlerFacade)
        {
            _blogHandlerFacade = blogHandlerFacade;
        }

        public ActionResult Index(Blog blog, int? entryCount)
        {
            if (!entryCount.HasValue) 
                entryCount = defaultEntryCount;  

            int totalItems;
            if(Request.IsAjaxRequest())
            {
                int page = entryCount.Value / defaultEntryCount;
                IEnumerable<Entry> pagedEntries = _blogHandlerFacade.GetLatestEntries(blog, page, defaultEntryCount, out totalItems);
                if(entryCount < totalItems)
                    AddMoreUrlToViewData(entryCount.Value);
                return View("EntryTeaserList", pagedEntries);
            }

            IEnumerable<Entry> entries = _blogHandlerFacade.GetLatestEntries(blog, 1, entryCount.Value, out totalItems);
            if (entryCount < totalItems)
                AddMoreUrlToViewData(entryCount.Value);

            if(entryCount.Value != defaultEntryCount)
                ViewData["nofollow"] = true;

            return View(entries);
        }

        private void AddMoreUrlToViewData(int entryCount)
        {
            ViewData["moreUrl"] = Url.Action("Index", "Home", new { entryCount = entryCount + defaultEntryCount });
        }
    }
}
